home *** CD-ROM | disk | FTP | other *** search
- In article <4gsi2p$905@bcarh8ab.bnr.ca>,
- brian (b.c.) white <bcwhite@bnr.ca> wrote:
- >In article <pgpmoose.199602221531.14635@isolde.mti.sgi.com>,
- >ian (i.) willmott <willmott@bnr.ca> wrote:
- >
- >>In an article entitled "Q: Generic Callbacks -- Object->*func(...)"
- >>(reference <4fti32$p3p@bcarh8ab.bnr.ca>), bcwhite@bnr.ca asks
- >
- >>"Does the C++ standard allow for a generic callback to be specified?
- >>Basically, I'd like to be able to pass an arbitrary object and
- >>function of that object to be called at some later time."
- >
- >>What is needed is the ability to use member functions as callbacks
- >>without any constraint on the type of the object they are invoked on.
- >>This is possible in C++ only by using various implementation-dependent
- >>hacks to escape the type system, because the language does not provide
- >>any way to express such a construct.
- >
- >Of course, what we're really trying to with all this is to pass _code_
- >(along with its context) as an object.
-
- There exist a rather simple solution using a static member function.
- Instead of having the callback call a normal member function it can
- call a static callback member function with the object as a
- argument. Then this callback function can call the real callback function.
- This will involve an extra callback function for each callback one has,
- but on the other hand it involves no changes to the base class if
- one want to override the real callback function in a derived class.
-
- class X
- {
- public:
- static void callback(void* to)
- virtual void real_callback();
- };
-
- void X::callback(void* to)
- {
- X* me = (X*)to;
- me ->real_callback()
- }
-
- Motif widget callbacks and event handlers are examples where this pattern
- works without problems.
-
- If the desired class Y can not be modified it is possible that X is a helper
- class that knows which member function on the real class Y it shall call.
- I.e. this solution is portable and can be used for all possible classes.
-
- Anders
-
-
-
- [ comp.std.c++ is moderated. To submit articles: Try just posting with your
- newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
- comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
- Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
- Comments? mailto:std-c++-request@ncar.ucar.edu
- ]
-